package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")//获取会员报告统计
        /**
         *
         * 给前端页面返回的数据为日期和对应的数据,返回的数据res.data.data.months/memberCount,封装在map中
         * map中封装两个list集合,分别表示月份和数量
         * 获取当前的时间往前计算一年
         * 根据获取的日期获取一个月的数据
         * 封装到map集合返回数据到页面
         */
        public Result getMemberReport(@RequestBody Map map) {
            String startTime = (String) map.get("startTime");
            String endTime = (String) map.get("endTime");
            Map<String, Object> m = new HashMap<>();
            List<String> months = new ArrayList();
            try {
                months = DateUtils.getMonthBetween(startTime, endTime, "yyyy.MM");
            } catch (Exception e) {
                e.printStackTrace();
            }
            m.put("months",months);
            List<Integer> memberCount = memberService.findMemberCountByMonths(months);
            m.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, m);
        }

    @RequestMapping("/getSetmealReport")//查询每个套餐所占的比重
    public Result getSetmealReport(){
        /**页面需要的数据为setmealName和setmealCount,使用map进行封装
         * 查询所有的套餐名称
         * 查询每个套餐的预约数量
         * 每个套餐的预约数量中的key就是套餐名称,所以直接查询套餐数量
         */
        try {
            Map<String,Object> map=new HashMap<>();
            List<String> setmealNames = new ArrayList<>();
            List<Map<String,Object>> setmealCount= setmealService.findSetmealCount();
            for (Map<String, Object> stringObjectMap : setmealCount) {
                String name = (String) stringObjectMap.get("name");
                setmealNames.add(name);
            }
            map.put("setmealNames",setmealNames);
            map.put("setmealCount",setmealCount);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")//运营数据统计--页面显示
    public Result getBusinessReportData(){
        //页面返回为response.data.data,把所有的数据封装在map中返回页面
        try {
            Map<String,Object> data=reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")//导出excel表
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /**
         * 使用poi技术操作表格涉及到行高背景等问题,所以通过读取模板文件的方式往表中添加数据
         * 获取模板文件的位置读取到内存中,然后再写出
         * 通过service拿出数据,按照单元格的位置填充内容
         */
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获取模板文件的位置
            String path=request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";
            Workbook workbook=new XSSFWorkbook(new FileInputStream(new File(path)));//获取工作簿
            Sheet sheet = workbook.getSheetAt(0);//获取表

            Row row = sheet.getRow(2);//获取第3行填充日期
            row.getCell(5).setCellValue(reportDate);

            row = sheet.getRow(4);//填充今日新增数和总会员数
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            row = sheet.getRow(5);//本周新增和本月新增
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);//今日预约和今日到访
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);//本周预约和本周到访
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);//本月预约和本月到访
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            //热点套餐填充
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                //先获取第13行,然后对rowNum进行自增,row=12,rowNum=13
                row=sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }
            //使用输出流进行表格下载,基于浏览器进行下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出pdf文件
    @RequestMapping("/exportBusinessReportPDF")
    public void exportBusinessReportPDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            //模板路径
            String jrxmlPath = "E:\\workspace\\health_parent\\health_backend\\src\\main\\resources\\health_business3.jrxml";
            String jasperPath = "E:\\workspace\\health_parent\\health_backend\\src\\main\\resources\\health_business3.jasper";

            //jasper编译
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            Map<String, Object> result = (Map<String, Object>) this.getBusinessReportData().getData();
            String reportDate = (String) result.get("reportDate");//获取当前日期
            Integer todayNewMember = (Integer) result.get("todayNewMember");//获取今日新增会员
            Integer totalMember = (Integer) result.get("totalMember");//获取所有会员数量
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");//获取本周新增会员数
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");//获取本月新增会员数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");//获取今天预约数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");//获取今天已到诊数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");//获取本周预约数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");//获取本周已到诊数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");//获取本月预约数
            Integer thisMonthVisitsNUmber = (Integer) result.get("thisMonthVisitsNumber");//获取本月已到诊数

            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

            Map<String, Object> map = new HashMap<>();
            map.put("reportDate", reportDate);
            map.put("todayNewMember", todayNewMember);
            map.put("totalMember", totalMember);
            map.put("thisWeekNewMember", thisWeekNewMember);
            map.put("thisMonthNewMember", thisMonthNewMember);
            map.put("todayOrderNumber", todayOrderNumber);
            map.put("todayVisitsNumber", todayVisitsNumber);
            map.put("thisWeekOrderNumber", thisWeekOrderNumber);
            map.put("thisWeekVisitsNumber", thisWeekVisitsNumber);
            map.put("thisMonthOrderNumber", thisMonthOrderNumber);
            map.put("thisMonthVisitsNUmber", thisMonthVisitsNUmber);

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, map, new JRBeanCollectionDataSource(hotSetmeal));


            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            //输出文件的路径
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //会员性别占比统计
    @RequestMapping("/getRatioOFGenderReport")
    public Result getRatioOFGenderReport(){
        try {
            //定义一个map集合用来存放前端需要的数据
            Map<String,Object> map = new HashMap();
            //用来存储会员性别的类别
            List<String> memberGenderNames = new ArrayList<>();
            //用来存储性别对应的数量
            List<Map<String,Object>> memberGenderCount = memberService.findGenderByMember();
            //遍历memberGenderCount
            for (Map<String, Object> stringObjectMap : memberGenderCount) {
                String name = (String) stringObjectMap.get("name");//获取性别
                memberGenderNames.add(name);//将性别的类别添加到memberGenderNames集合中
            }
            map.put("memberGenderNames",memberGenderNames);
            map.put("memberGenderCount",memberGenderCount);
            return new Result(true,MessageConstant.GET_MEMBER_RatioGender_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_RatioGender_REPORT_REPORT_FAIL);
        }
    }

    //会员年龄占比统计
    @RequestMapping("/getRatioOFAgeReport")
    public Result getRatioOFAgeReport(){
        try {
            Map<String, Object> map = new HashMap<>();
            List<String> memberAgeNames = new ArrayList<String>();
            List<Map<String,Object>> memberAgeCount = memberService.findAgeByMember();
            for (Map<String, Object> stringObjectMap : memberAgeCount) {
                String name = (String) stringObjectMap.get("name");
                memberAgeNames.add(name);
            }
            map.put("memberAgeNames",memberAgeNames);
            map.put("memberAgeCount",memberAgeCount);
            return new Result(true,MessageConstant.GET_MEMBER_RatioAge_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_RatioAge_REPORT_REPORT_FAIL);
        }
    }
}
